package com.bicon.botu.mall.component.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.bicon.botu.mall.component.common.AppVersionConstants;
import com.bicon.botu.mall.component.entity.AppVersion;
import com.bicon.botu.mall.component.service.IAppVersionService;
import com.bicon.botu.core.base.common.controller.BaseController;
import com.bicon.botu.core.base.common.entity.BaseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author: 吕祥
 * @Date: Created in 8:49 2017/10/18/018
 */
@Controller
@RequestMapping("/V1.0.0/api/base/appVersion")
public class AppVersionApi extends BaseController {

    @Autowired
    IAppVersionService iAppVersionService;

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult test() {
        return sendResult200();
    }

    /**
     * 检查新版本
     *
     * @param versionCode   版本号
     * @return
     */
    @RequestMapping(value = "/checkingver", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult checkingver(@RequestParam Integer versionCode) {
        if (StringUtils.isAnyBlank(String.valueOf(versionCode))) {
            return sendResult400();
        }
        return iAppVersionService.checkingver(versionCode);
    }

    /**
     * 获取最新app下载地址，并跳转下载
     * @param response
     */
    @RequestMapping(value = "/apk", method = RequestMethod.GET)
    public void apk(HttpServletResponse response) {
        List<AppVersion> list = new AppVersion().selectList(new EntityWrapper().eq("state", AppVersionConstants.RELEASE).orderBy("version_code", false));
        if(list != null && list.size() > 0){
            try {
                response.sendRedirect(list.get(0).getUrl());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
